// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var router = require("../hash/pageRouter");
	var css_loanNotice = require("./loanNotice.css");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var constant = require("constant");
	var tools = require("tools");
	var pageIndex = 1,
		pageSize = 20,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var financeId;
	var recieveNoticeId;
	var financeNumber;
	var totalLoanAmount;
	var js_platform_main = require("./platform_main.js");
	var fileUuid;
	var loanNoticeId;
	var productType;
	var left;
	var financeAmount;
	var caseSizeMap = new tools.Map();
	var enterpriseId;
	var init = function(page) {
		recieveNoticeId = page.params.recieveNoticeId || base.getUrlParam("recieveNoticeId");
		financeId = page.params.financeId || base.getUrlParam("financeId");
		left = page.params.left || base.getUrlParam("left");
		js_platform_main.init(0);
		caseSizeMap.toString = function() {
			var str = "";
			for (var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
				if (this.container[keys[i]] == 0) {
					continue;
				}
				str = str  + this.container[keys[i]] + "X" + keys[i] + "<br/>";
			}
			return (str == "" ? "箱体情况：无" : "箱体情况：" + str);
		}
		
		$(".left").removeClass("none");
		leftMenu.init(6);
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		$("#main").css("background", "#ffffff");
		$("#leftMenu7").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu7 .leftMenu li:first-child").addClass("leftMenu-open");
		$("#leftMenu7").find(".leftMenu-item").eq(left).addClass("leftMenu-active");
		pageIndex = 1;
		inquireFinanceApplicationDetail();

		initEvent();
		router.init();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		
		$("#loanNotice").on("click", ".inventoryIdCheckedsAll", function(){
			var evaluateValuations = 0;
			caseSizeMap.put("10GP", 0);
			caseSizeMap.put("20GP", 0);
			caseSizeMap.put("40GP", 0);
			caseSizeMap.put("48GP", 0);
			caseSizeMap.put("10HQ", 0);
			caseSizeMap.put("20HQ", 0);
			caseSizeMap.put("40HQ", 0);
			caseSizeMap.put("48HQ", 0);
			caseSizeMap.put("10RH", 0);
			caseSizeMap.put("20RH", 0);
			caseSizeMap.put("40RH", 0);
			caseSizeMap.put("48RH", 0);
			if ($(this).prop("checked")) {
				$("#loanNotice .inventoryIdCheckeds").prop("checked", true);
			} else {
				$("#loanNotice .inventoryIdCheckeds").prop("checked", false);
			}
			$.each($("#loanNotice .inventoryId:checked"), function(i, val) {
				statisticalCaseSize(caseSizeMap, $.trim($(this).parents("tr").find(".caseSize").html()));
				var e = $(this).parent().parent().find(".financeValuations").html()*1 + $(this).parent().parent().find(".adjustment").html()*1;
				if ($.trim(e) == "") {
					e = 0;
				}
				evaluateValuations += parseFloat(e);
			});
			$(".case_info").html(caseSizeMap.toString());
			$("#loanAmount").val(evaluateValuations.toFixed(2));
			$("#loanNotice .input-loan-amount1").html(tools.formatCurrency(evaluateValuations.toFixed(2)));
		});
		
		//点击首页
		$(".platform_main").unbind("click").click(function() {
			top.location.href = "../main/platform_main.html";
		});

		//列表
		$(".loanNoticeList").unbind("click").click(function() {
			router.route("main/loanNotice_list.html?left=4", true);
		});

		//点击上传附件
//		$("#loanNotice").on("change", "#loanIntro", function() {
//			uploadFile();
//		});

		$("#loanNotice").on("click", ".deleteLoanIntro", function() {
			$(this).parent().remove();
		});

		//点击理货 详情
		$("#tallyingListBody").on("click", ".tallyingListDetail", function() {
			var inventoryId = [];
			var $this = $(this).parents("tr.tr_style");
			inventoryId.push($this.attr("inventoryId"));
			router.route("financing/tallyDetail.html?inventoryId=" + inventoryId + "&recieveNoticeId=" + recieveNoticeId + "&type=readOnly&financeId=" + financeId, true);
		});
		
		//金额change事件
		$("#loanNotice").on("change", "#loanAmount", function() {
			$("#loanNotice .input-loan-amount1").html(tools.formatCurrency($(this).val()));
		});

		//点击放款确认
		$(".loanNoticeSubmit").on("click", function() {
			if (totalLoanAmount*1 != $("#loanAmount").val()*1) {
				dialog.showConfirmDialog("放款确认","请检查放款金额，是否确认放款？", function(){
					createLoanNotice();
				});
			} else {
				createLoanNotice();
			}
		});
	};
	
	//查询放款确认-融资信息列表
	var inquireFinanceApplicationDetail = function() {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					
					productType = data.datas[0].productType;
					financeNumber = data.datas[0].financeNumber;
					totalLoanAmount = data.datas[0].totalLoanAmount;
					financeAmount = data.datas[0].financeAmount;
					var noLoanAmount = financeAmount - totalLoanAmount;
					enterpriseId = data.datas[0].enterpriseId;
					$(".loan_amount").html("￥" + totalLoanAmount);
					$(".financeAmount").html("￥" + financeAmount);
					$(".no_Loan_amount").html("￥" + noLoanAmount.toFixed(2));
					$(".loan_amount1").html("￥" + tools.formatCurrency(totalLoanAmount));
					$(".financeAmount1").html("￥" + tools.formatCurrency(financeAmount));
					$(".no_Loan_amount1").html("￥" + tools.formatCurrency(noLoanAmount.toFixed(2)));
					$("input[name=enterpriseName]").val(data.datas[0].enterpriseName);
					databind.fillForm($(".loanNoticeContent"), {
						financeId: financeId,
						financeNumber: financeNumber
					});
					
					inquireEnterpriseDetail(data.datas[0].enterpriseId);
					inquireSystemBlankInfo();
					
					$.each(data.datas[0].financeFilesInfoList, function(){
						$.each(this.filesUuid.split(","), function() {
							var _this = this;
							if (_this != null && $.trim(_this) != "") {
								//&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteLoanIntro">x</a>
								var str = '<div class="showloanIntroDiv"><a target="_blank" class="mas showloanIntro" id="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '">' + tools.inquireFile(_this) + '</a></div>'
								$(".loanIntro").before(str);
								saveMaterials();
							}
						});
					});
					
					inquireWaitLoanNoticeBulkstockInventoryPageList();
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//查询平台银行账户
	var inquireSystemBlankInfo = function() {
			base.fnAjax({
				action: "inquireSystemBlankInfo.json",
				oData: {}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						$("#loanBank").val(data.datas[0].depositBank);
						$("#loanCreditCard").val(data.datas[0].creditCard);
						data.datas[0].accountHolder;
						data.datas[0].creditCard;
					} else {
						base.alert(2, "信息获取失败");
					}
				}
			});
		}
		//查询企业明细 --企业银行账户
	var inquireEnterpriseDetail = function(enterpriseId1) {
			base.fnAjax({
				action: "inquireEnterpriseDetail.json",
				oData: {
					enterpriseId: enterpriseId1
				}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						$("#beneficiaryName").val(data.datas[0].accountHolder);
						$("#beneficiaryBank").val(data.datas[0].depositBank);
						$("#beneficiaryCreditCard").val(data.datas[0].creditCard);
						data.datas[0].accountHolder;
						data.datas[0].creditCard;
					} else {
						base.alert(2, "信息获取失败");
					}
				}
			});
		}
		//创建放款通知
	var createLoanNotice = function() {
		var inventoryId = [];
		$.each($(".inventoryId:checked"), function(i, val) {
			inventoryId[i] = $(this).attr("inventoryId");
			$(this).val($(this).attr("inventoryId"));
		});
		if (inventoryId.length == 0) {
			base.alert(2, "请选择放款箱");
			return;
		}
		databind.submitDom($(".loanNoticeContent"), function() {
			base.alert(1, "放款申请提交成功");
			js_platform_main.init(0);
			router.route("main/loanNotice_list.html?left=4");
		});
	}

	var inquireWaitLoanNoticeBulkstockInventoryPageList = function() {
		base.fnAjax({
			action: "inquireWaitLoanNoticeBulkstockInventoryPageList.json",
			async: false,
			oData: {
				financeId: financeId,
				pageIndex: pageIndex,
				pageSize: pageSize
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("formatCurrency", tools.formatCurrency);
					if (productType == 3 || productType == 5 || productType == 6) {
						$("#loanNotice .loan_tr").remove();
						var tpl = $("#bulkstockLoanNoticeTpl1").html();
						var html = juicer(tpl, data);
						$("#bulkstockLoanNoticeListBody").append(html);
					} else {
						$("#loanNotice .loan_tr1").remove();
						var tpl = $("#bulkstockLoanNoticeTpl").html();
						var html = juicer(tpl, data);
						$("#bulkstockLoanNoticeListBody").append(html);
					}

					inventoryIdCheckedsEeven();
					//货箱总应款bulkstockValuation
					$.each($(".financeValuations"), function(i, val) {
						var $this = $(this);
						if ($this.parents("tr").attr("type") == '2') {
							var financeValuations = $this.parents("tr").attr("settlementPrice")*1 + $this.parents("tr").attr("adjustment")*1;
							$this.html(financeValuations.toFixed(2));
							$this.parent().find(".financeValuations1").html(tools.formatCurrency($this.html()));
						} else {
							var financeValuations = 0;
							$.each($this.parents("tr").find(".financeValuation"), function(i, val) {
								financeValuations = financeValuations + parseFloat($(this).html());
							});
							$this.html(financeValuations.toFixed(2));
							$this.parent().find(".financeValuations1").html(tools.formatCurrency($this.html()));
						}
					});
					//货箱总估值
					$.each($(".bulkstockValuations"), function(i, val) {
						var bulkstockValuations = 0;
						$.each($(this).parents("tr").find(".bulkstockValuation"), function(i, val) {
							bulkstockValuations = bulkstockValuations + parseFloat($(this).html());
						});
						$(this).html(bulkstockValuations);
					});

					$("#loanNotice .detail").unbind("click").click(function(){
						var $this = $(this);
						if (productType == 3 || productType == 5 || productType == 6) {
							router.route("main/wareHouseDetail.html?caseNumber=" + $this.parents("tr").attr("caseNumber") + "&financeNumber=" + $this.parents("tr").attr("financeNumber"));
//							router.route("main/wareHouseDetail.html?caseNumber=R-SH002-1706010008&financeNumber=" + $this.parents("tr").attr("financeNumber"));
						} else {
							router.route("bulkstockTallyDetail/bulkstockTallyDetail.html?inventoryId=" + $this.parents("tr").attr("inventoryId"));
						}
					});
					
					setTimeout(function(){
						if (pageIndex <= data.totalPageCount) {
							pageIndex ++;
							inquireWaitLoanNoticeBulkstockInventoryPageList();
						} else {
							for (var i = 0; i < $("#loanNotice .index").length; i++) {
								$($("#loanNotice .index")[i]).html(i+1);
							}
						}
					}, 10);
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}
	
	//箱号点击事件
	var inventoryIdCheckedsEeven = function() {
		$("#loanNotice .inventoryIdCheckeds").unbind("click").click(function() {
			var evaluateValuations = 0;
			caseSizeMap.put("10GP", 0);
			caseSizeMap.put("20GP", 0);
			caseSizeMap.put("40GP", 0);
			caseSizeMap.put("48GP", 0);
			caseSizeMap.put("10HQ", 0);
			caseSizeMap.put("20HQ", 0);
			caseSizeMap.put("40HQ", 0);
			caseSizeMap.put("48HQ", 0);
			caseSizeMap.put("10RH", 0);
			caseSizeMap.put("20RH", 0);
			caseSizeMap.put("40RH", 0);
			caseSizeMap.put("48RH", 0);
			if ($("#loanNotice .inventoryId:checked").length != $("#loanNotice .inventoryId").length) {
				$("#loanNotice .inventoryIdCheckedsAll").prop("checked", false);
			} else {
				$("#loanNotice .inventoryIdCheckedsAll").prop("checked", true);
			}
			$.each($("#loanNotice .inventoryId:checked"), function(i, val) {
				statisticalCaseSize(caseSizeMap, $.trim($(this).parents("tr").find(".caseSize").html()));
				var e = $(this).parent().parent().find(".financeValuations").html()*1 + $(this).parent().parent().find(".adjustment").html()*1;
				if ($.trim(e) == "") {
					e = 0;
				}
				evaluateValuations += parseFloat(e);
			});
			$(".case_info").html(caseSizeMap.toString());
			$("#loanAmount").val(evaluateValuations.toFixed(2));
			$("#loanNotice .input-loan-amount1").html(tools.formatCurrency(evaluateValuations.toFixed(2)));
		});
	}
	
	var statisticalCaseSize = function(m, c) {
		switch (c){
			case "10GP":
				m.put("10GP", m.get("10GP")*1 + 1);
				break;
			case "20GP":
				m.put("20GP", m.get("20GP")*1 + 1);
				break;
			case "40GP":
				m.put("40GP", m.get("40GP")*1 + 1);
				break;
			case "48GP":
				m.put("48GP", m.get("48GP")*1 + 1);
				break;
			case "10HQ":
				m.put("10HQ", m.get("10HQ")*1 + 1);
				break;
			case "20HQ":
				m.put("20HQ", m.get("20HQ")*1 + 1);
				break;
			case "40HQ":
				m.put("40HQ", m.get("40HQ")*1 + 1);
				break;
			case "48HQ":
				m.put("48HQ", m.get("48HQ")*1 + 1);
				break;
			case "10RH":
				m.put("10RH", m.get("10RH")*1 + 1);
				break;
			case "20RH":
				m.put("20RH", m.get("20RH")*1 + 1);
				break;
			case "40RH":
				m.put("40RH", m.get("40RH")*1 + 1);
				break;
			case "48RH":
				m.put("48RH", m.get("48RH")*1 + 1);
				break;
			default:
				break;
		}
	}

	//上传文件
//	var uploadFile = function() {
//		if ($("#loanIntro").val() != "") {
//			$.ajaxFileUpload({
//				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
//				secureuri: false,
//				fileElementId: 'loanIntro',
//				dataType: 'json',
//				success: function(data) {
//					var str = '<div class="showloanIntroDiv"><a target="_blank" class="mas showloanIntro" id="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteLoanIntro">x</a></div>'
//					$(".loanIntro").before(str);
//					saveMaterials();
//				},
//				complete: function(xml) {
//					$("#loanIntro").change(function() {
//						uploadFile();
//					});
//				},
//				error: function(data, status, e) {
//					if (data.msg == null) {
//						base.alert(2, "文件太大无法上传");
//					} else {
//						base.alert(2, data.msg);
//					}
//				}
//			});
//		} else {
//			base.alert(3, "请选择文件！");
//		}
//	};
	//更新fileUuuid保存字段
	var saveMaterials = function() {
		var materials = "";
		var number = $(".showloanIntro").length;
		$(".showloanIntro").each(function(i, object) {
			if (i == number - 1) {
				materials += object.id;
			} else {
				materials += object.id + ",";
			}

		});
		$(".fileUuids").val(materials);
	}
	return {
		init: init
	};
});